/*
 * @Author: 飞越疯人院 353362604@qq.com
 * @Date: 2022-11-18 15:59:32
 * @LastEditors: 飞越疯人院 353362604@qq.com
 * @LastEditTime: 2022-11-21 13:49:55
 * @FilePath: \adminstration\src\Common\Modal\MoreModal\EditTableModalTwo.jsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { EditableProTable } from '@ant-design/pro-components'
import { useBoolean, useLatest } from 'ahooks'
import { Button, message, Spin } from 'antd'
import axios from 'axios'
import { useState, useEffect } from 'react'
import { v4 as uuidv4 } from 'uuid'

export const EditTableModalTwo = ({ CurrentData, Scroll }) => {
    const [loading, { setTrue, setFalse }] = useBoolean(true)
    const [dataSource, setDataSource] = useState([])
    const [editableKeys, setEditableRowKeys] = useState()
    const dataSourceLatest = useLatest(dataSource)
    useEffect(() => {
        const { get, params } = CurrentData
        axios.get(get, { params }).then(({ data }) => {
            const { list } = data
            setDataSource(list)
            setEditableRowKeys(list.map(item => item.uuid))
            setFalse()
        })
    }, [CurrentData, dataSourceLatest, setFalse])

    const SubmitData = () => {
        setTrue()
        const { additional, field, pos } = CurrentData
        let data = []
        dataSource.forEach(e => {
            let item = {}
            field.forEach(key => {
                item = { ...item, [key]: e[key], ...additional }
            })
            data = [...data, item]
        })
        axios
            .post(pos, data)
            .then(res => {
                message.success('字段保存成功')
                setFalse()
            })
            .catch(() => {
                message.error('不能保存空值')
                setFalse()
            })
    }
    return (
        <Spin spinning={loading}>
            <EditableProTable
                rowKey="uuid"
                columns={CurrentData.columns}
                scroll={Scroll}
                value={dataSource}
                onChange={setDataSource}
                recordCreatorProps={{ newRecordType: 'dataSource', record: () => ({ uuid: uuidv4() }) }}
                toolBarRender={() => {
                    return [
                        <Button type="primary" key="save" onClick={SubmitData}>
                            保存数据
                        </Button>,
                    ]
                }}
                editable={{
                    type: 'multiple',
                    editableKeys,
                    actionRender: (_, __, defaultDoms) => [defaultDoms.delete],
                    onValuesChange: (_, recordList) => setDataSource(recordList),
                    onChange: editableKeys => setEditableRowKeys(editableKeys),
                }}
            />
        </Spin>
    )
}
